package com.guaigen.campus.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.guaigen.campus.common.exception.BusinessException;
import com.guaigen.campus.common.exception.BusinessExceptionEnum;
import com.guaigen.campus.common.util.JwtUtil;
import com.guaigen.campus.common.util.SnowUtil;
import com.guaigen.campus.member.domain.Member;
import com.guaigen.campus.member.domain.MemberExample;
import com.guaigen.campus.member.mapper.MemberMapper;
import com.guaigen.campus.member.req.MemberLoginReq;
import com.guaigen.campus.member.req.MemberRegisterReq;
import com.guaigen.campus.member.req.MemberSendCodeReq;
import com.guaigen.campus.member.resp.MemberLoginResp;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class MemberService {

    private static final Logger LOG = LoggerFactory.getLogger(MemberService.class);

    @Resource
    MemberMapper memberMapper;

    public int count() {
        return (int) memberMapper.countByExample(null);
    }

    public Long register(MemberRegisterReq req) {
        String mobile = req.getMobile();
        Member memberDB = selectByMobile(mobile);

        if (!ObjectUtil.isNull(memberDB)) {
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_EXIST);
        }

        Member member = new Member();
        member.setId(SnowUtil.getSnowflakeNestId());
        member.setMobile(mobile);
        memberMapper.insert(member);
        return member.getId();
    }

    public void sendCode(MemberSendCodeReq req) {
        String mobile = req.getMobile();
        Member memberDB = selectByMobile(mobile);

        // 如果手机号不存在，则插入一条记录
        if (ObjectUtil.isNull(memberDB)) {
            LOG.info("手机号不存在，插入一条记录");
            Member member = new Member();
            member.setMobile(mobile);
            member.setId(SnowUtil.getSnowflakeNestId());
            memberMapper.insert(member);
        } else {
            LOG.info("手机号存在，不插入记录");
        }

        // 生成验证码（由于没有对接短信通道，暂用常量模拟）
//        String code = RandomUtil.randomString(6);
        String code = "8888";

        LOG.info("生成短信验证码：{}", code);

        // 保存短信记录表：手机号、短信验证码、有效期、是否已使用、业务类型、发送时间、使用时间
        LOG.info("保存短信记录表");

        // 对接短信通道，发送短信
        LOG.info("对接短信通道");
    }

    public MemberLoginResp login(MemberLoginReq req) {
        String mobile = req.getMobile();
        String code = req.getCode();
        Member memberDB = selectByMobile(mobile);

        // 如果手机号不存在，抛出请获取验证码并输入
        if (ObjectUtil.isNull(memberDB)) {
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_NOT_EXIST);
        }

        // 从数据库或者缓存中获取短信验证码验证
        if (!"8888".equals(code)) {
            throw new BusinessException(BusinessExceptionEnum.MEMBER_MOBILE_CODE_ERROR);
        }

        // 包装成返回类
        MemberLoginResp memberLoginResp = BeanUtil.copyProperties(memberDB, MemberLoginResp.class);

        // jwt生成token
        Map<String, Object> stringObjectMap = BeanUtil.beanToMap(memberLoginResp);
        String token = JwtUtil.createToken(memberLoginResp.getId(), memberLoginResp.getMobile());
        memberLoginResp.setToken(token);

        // 验证通过则返回一些数据
        return memberLoginResp;
    }

    private Member selectByMobile(String mobile) {
        MemberExample memberExample = new MemberExample();
        memberExample.createCriteria().andMobileEqualTo(mobile);
        List<Member> list = memberMapper.selectByExample(memberExample);

        if (CollUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }
}
